package top.wshape1.rpc.consumer.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.Promise;
import lombok.extern.slf4j.Slf4j;
import top.wshape1.rpc.common.constant.RpcMessageCodeEnum;
import top.wshape1.rpc.consumer.CallFutureHolder;
import top.wshape1.rpc.filter.FilterChain;
import top.wshape1.rpc.filter.FilterChainFactory;
import top.wshape1.rpc.message.RpcResponse;

/**
 * @author Wshape1
 * @version 1.0
 * @description 接收调用响应消息的入站处理器
 * @since 2024-02-02
 */

@Slf4j
@ChannelHandler.Sharable
public class RpcResponseHandler extends SimpleChannelInboundHandler<RpcResponse> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcResponse msg) throws Exception {

        FilterChain filterChain = FilterChainFactory.getConsumerRecRespFilterChain();
        try {
            if (!filterChain.doFilter(msg)) {
                log.debug("doFilter return false. msg: {}", msg);
                return;
            }
        } finally {
            filterChain.clearLocal();
        }

        log.debug("接受到序列号为{}的请求消息，内容：{}", msg.getSequenceId(), msg);

        Promise<Object> promise = CallFutureHolder.remove(msg.getSequenceId());
        if (promise != null) {
            Object result = msg.getResult();
            Exception exception = msg.getException();
            if (msg.getCode() != RpcMessageCodeEnum.RPC_OK.getCode()) {
                promise.setFailure(exception);
            } else {
                log.debug("收到的返回结果：{}，类型：{}", result, result.getClass());
                promise.setSuccess(result);
            }
        }
    }
}
